package com.Adapters.Items;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.Adapters.CommentAdapter;
import com.Animations.AnimUtil;
import com.Animations.AnimUtil.AnimationCompleted;
import com.Animations.AnimationLists;
import com.Data.Comment;
import com.Data.Comment.onDeleteComentsCompleted;
import com.Downloaders.ProfilePictureDownloader;
import com.Downloaders.ProfilePictureDownloader.onProfilePictureDownloaded;
import com.Managers.FragmentManagerClass;
import com.Managers.UserManagerClass;
import com.TextFormat.UtilFonts;
import com.UtilDate.UtilDate;
import com.activities.ActivityProfileUser;
import com.shareup.R;
import com.utils.ShowToastClass;


public class ItemComment implements ItemPost {

    private CommentAdapter adapter;

    private boolean animate;

    private Comment comment;

    private Context context;

    private ViewHolder holder;

    private int idOwner;

    private LayoutInflater inflater;

    class MenuPopUpClick implements OnItemClickListener {

        private final AlertDialog dialog;

        public MenuPopUpClick(AlertDialog dialog) {

            this.dialog = dialog;
        }

        @SuppressWarnings("deprecation")
        @SuppressLint("NewApi")
        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {

            TextView text = (TextView) v.findViewById(android.R.id.text1);
            //
            if (text.getText().equals(v.getResources().getString(R.string.string_copy))) {
                String com = comment.getPicture().getUser().getRealName()
                            + ": " + comment.getMessage();
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
                    ClipData clip = ClipData.newPlainText("simple text", com);
                    ClipboardManager ClipMan = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipMan.setPrimaryClip(clip);
                }
                else {
                    ClipboardManager cm = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                    cm.setText(com);
                }

                ShowToastClass.message(v.getResources().getString(R.string.string_copied), v.getContext());
            }
            else
                if (text.getText().equals(v.getResources().getString(R.string.string_delete))) {
                    delete();
                }
            dialog.cancel();

        }
    }

    class OptionsShowListener implements OnLongClickListener {

        @Override
        public boolean onLongClick(View v) {

            String[] menu = new String[1];
            if (comment.getPicture().getUser().getID() == UserManagerClass.UserLogged.getID()
                        || UserManagerClass.UserLogged.getID() == idOwner) {
                menu = new String[2];
                menu[1] = context.getResources().getString(R.string.string_delete);
            }
            menu[0] = context.getResources().getString(R.string.string_copy);

            ArrayAdapter<String> adapterI = new ArrayAdapter<String>(v.getContext(), android.R.layout.simple_list_item_1, menu);
            showOptionsDialog(adapterI);
            return false;
        }

        private void showOptionsDialog(ArrayAdapter<?> ladapter) {

            View view = inflater.inflate(R.layout.dialog_action_list, null);
            //
            ListView OptionsComment = (ListView) view.findViewById(R.id.item_list);
            OptionsComment.setAdapter(ladapter);
            AlertDialog.Builder dl = new AlertDialog.Builder(context);
            dl.setView(view);
            AlertDialog alert = dl.create();
            OptionsComment.setOnItemClickListener(new MenuPopUpClick(alert));
            alert.show();
            //
        }
    }

    class ViewClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {

            {
                showProfilePopUp();
            }
        }
    }

    class ViewHolder {

        public TextView comment;

        public RelativeLayout container;

        public TextView date;

        public TextView name;

        public ImageView profile;
    }

    public ItemComment(int idOwner, LayoutInflater inflater,
                Comment comment, CommentAdapter adapter) {

        super();
        this.comment = comment;
        this.inflater = inflater;
        this.context = adapter.getContext();
        this.adapter = adapter;
        this.idOwner = idOwner;

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.ItemPost#AnimateIn()
     */
    @Override
    public void AnimateIn() {

        AnimUtil.animateFadeIn(holder.profile, new AnimationCompleted() {

            @Override
            public void Completed() {

                AnimUtil.PostIn(context, holder.container, null);

            }
        });

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.ItemPost#AnimateOut(com.Animations.AnimUtil.
     * AnimationCompleted)
     */
    @Override
    public void AnimateOut(final AnimationCompleted callback) {

        // IF THE COMMENT ISNT IN THE LIST WE ANIMATE IT
        AnimUtil.PostOut(context, holder.container, new AnimationCompleted() {

            @Override
            public void Completed() {

                AnimUtil.animateFadeOut(holder.profile, callback);

            }
        });

    }

    @Override
    public void clearAnimatonList() {

        AnimationLists.displayedComments.clear();

    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.ItemPost#delete()
     */
    @Override
    public void delete() {

        AlertDialog.Builder dg = new AlertDialog.Builder(context);
        View v = inflater.inflate(R.layout.dialog_actions, null);

        TextView message = (TextView) v.findViewById(R.id.message_dialog);
        UtilFonts.setTextRegularFont(message);
        Button accept = (Button) v.findViewById(R.id.dialog_action_a_button);
        UtilFonts.setTextRegularFont(accept);
        Button cancel = (Button) v.findViewById(R.id.dialog_action_c_button);
        UtilFonts.setTextRegularFont(cancel);
        //
        message.setText(R.string.dialog_question_delete_comment_message);
        //
        dg.setView(v);
        //
        final AlertDialog alert = dg.create();
        accept.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Comment com = new Comment(v.getContext());
                com.setAction(Comment.ACTION_DELETE);
                com.setIDComment(comment.getIDComment());

                com.setCallbackDelete(new onDeleteComentsCompleted() {

                    @Override
                    public void Completed(String result) {

                        AnimateOut(new AnimationCompleted() {

                            @Override
                            public void Completed() {

                                adapter.remove(comment);
                                holder.container.setVisibility(View.VISIBLE);
                                holder.profile.setVisibility(View.VISIBLE);

                            }
                        });
                    }
                });
                com.execute();

                alert.cancel();
            }
        });
        cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                alert.cancel();
            }
        });

        alert.show();

    }

    public Comment getComment() {

        return comment;
    }

    @Override
    public int getCommentsCount() {

        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public int getLikesCount() {

        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public int getPostId() {

        return comment.getIDComment();
    }

    @Override
    public String getPublicationDate() {

        return comment.getPicture().getPublicationDate();
    }

    @Override
    public View getView(View v, int position) {

        if (v == null) {

            v = inflater.inflate(R.layout.item_comment, null);

            holder = new ViewHolder();

            holder.comment = (TextView) v.findViewById(R.id.c_text_comment);
            holder.name = (TextView) v.findViewById(R.id.c_text_name);
            holder.container = (RelativeLayout) v.findViewById(R.id.container_texts);
            holder.date = (TextView) v.findViewById(R.id.c_text_date_info);
            holder.profile = (ImageView) v.findViewById(R.id.c_image_profile);

            UtilFonts.setTextBoldFont(holder.name);
            UtilFonts.setTextRegularFont(holder.comment, holder.date);

            v.setTag(holder);

        }
        else {

            holder = (ViewHolder) v.getTag();
        }

        if (!AnimationLists.displayedComments.contains(comment.getIDComment())) {
            AnimationLists.displayedComments.add(comment.getIDComment());
            holder.container.setVisibility(View.INVISIBLE);
            holder.profile.setVisibility(View.INVISIBLE);
            animate = true;

        }

        setTexts();

        return v;
    }

    @Override
    public int getViewType() {

        return RowType.COMMENT.ordinal();
    }

    @Override
    public void setCommentsCount(int count) {

        // TODO Auto-generated method stub

    }

    @Override
    public void setLikesCount(int count) {

        // TODO Auto-generated method stub

    }

    public void showProfilePopUp() {

        Intent intent = new Intent(context, ActivityProfileUser.class);
        intent.putExtra("imgprofile", comment.getPicture().getUser().getProfilePicture());
        intent.putExtra("nameprofile", comment.getPicture().getUser().getRealName());
        intent.putExtra("IDUSER", comment.getPicture().getUser().getID());
        //
        context.startActivity(intent);
        AnimUtil.getActivityTransition(FragmentManagerClass.aComment, true);
    }

    @Override
    public void updatePublicationDate(String newDate) {

        comment.getPicture().setPublicationDate(newDate);

    }

    private void animateIn() {

        if (animate) {
            animate = false;
            AnimateIn();
        }
    }

    private void DownloadProfilePicture() {

        String url = comment.getPicture().getUser().getProfilePicture();

        int idu = comment.getPicture().getUser().getID();
        if (idu == UserManagerClass.UserLogged.getID()) {
            holder.profile.setImageDrawable(FragmentManagerClass.aMenu.getProfile().getDrawable());
            animateIn();
        }
        else {
            ProfilePictureDownloader pd = new ProfilePictureDownloader();
            pd.setCallbackProfilePicture(new onProfilePictureDownloaded() {

                @Override
                public void completed(Bitmap result) {

                    holder.profile.setImageBitmap(result);
                    animateIn();

                }
            });
            pd.execute(url);
        }

    }

    private void setTexts() {

        if (comment.getPicture().getPublicationDate() != holder.date.getTag()) {
            holder.date.setText("");
            holder.date.setTag(comment.getPicture().getPublicationDate());
            UtilDate dt = new UtilDate(this.context);
            dt.setTimeDifference(comment.getPicture().getPublicationDate(), holder.date);
        }
        holder.name.setText(comment.getPicture().getUser().getRealName());
        holder.comment.setText(comment.getMessage());

        holder.name.setOnClickListener(new ViewClickListener());
        holder.profile.setOnClickListener(new ViewClickListener());
        holder.container.setOnLongClickListener(new OptionsShowListener());
        DownloadProfilePicture();
    }

    /*
     * (non-Javadoc)
     * @see com.Adapters.Items.ItemPost#getPosition()
     */
    @Override
    public int getPosition() {

        // TODO Auto-generated method stub
        return 0;
    }
}
